package com.ctg.behavior.calc.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.ctg.behavior.common.calc.CtCalcPropertyType;
import com.ctg.behavior.common.consts.CtPropertyConsts;

public class CtCalcPropertyUtils {

	public static CtCalcPropertyType getValueType(String field) {
		CtCalcPropertyType pType = new CtCalcPropertyType();
		if (StringUtils.isEmpty(field)) {
			return pType;
		}
		String[] items = field.split("\\.");
		if (items[0].equalsIgnoreCase("event")) {
			pType.setType(CtPropertyConsts.PROPERTY_EVENT);
			pType.setEvent(items[1]);
			pType.setProperty(items[2]);
		} else if (items[0].equalsIgnoreCase("user")) {
			pType.setType(CtPropertyConsts.PROPERTY_USER);
			pType.setProperty(items[1]);
		} else {
			pType.setType("");
			// 临时方案, 应对field就是一个属性编码的情况
			pType.setProperty(items[0]);
		}
		return pType;
	}

	// 获得事件属性或用户属性字段
	public static String getProperty(String field) {
		CtCalcPropertyType pType = CtCalcPropertyUtils.getValueType(field);
		return pType.getProperty();
	}

	// 获得事件属性或用户属性字段
	public static List<String> getProperties(List<String> byFields) {
		List<String> properties = new ArrayList<>();
		for (String oneField : byFields) {
			CtCalcPropertyType ptype = CtCalcPropertyUtils.getValueType(oneField);
			properties.add(ptype.getProperty());
		}
		return properties;
	}

	// 获得事件标识, 查找对应fields信息
	public static CtCalcPropertyType findField(String eventId, List<String> fields) {
		for (String oneField : fields) {
			CtCalcPropertyType pType = CtCalcPropertyUtils.getValueType(oneField);
			if (eventId.equals(pType.getEvent())) {
				return pType;
			}
		}
		return null;
	}

	// 获得事件标识, 查找对应fields信息
	public static List<String> findEvents(List<String> eventIds, List<String> fields) {
		List<String> fieldEvents = new ArrayList<>();
		Set<String> eventsSet = new HashSet<String>(eventIds);
		for (String oneField : fields) {
			CtCalcPropertyType pType = CtCalcPropertyUtils.getValueType(oneField);
			if (eventsSet.contains(pType.getEvent())) {
				fieldEvents.add(pType.getEvent());
			}
		}
		return fieldEvents;
	}

}
